#pragma once

#include <vector>
#include <string>
#include "../database.hpp"
#include "../except.hpp"
#include "../libs/easylog.h"
#include "medicinemodel.hpp"
#include "purchase.hpp"

namespace pharmacy_server
{
    class PurchaseModel
    {
    public:
        bool create_purchase_order(const std::string& medicine_name, const std::string& supplier, int quantity, const std::string& purchase_date)
        {
            try
            {
                easymysql::result res = easymysql::executer(database::instance())(R"(
INSERT INTO purchase_records (medicine_name, supplier, quantity, purchase_date) VALUES ('{}', '{}', {}, '{}')
                )", medicine_name, supplier, quantity, purchase_date);

                MedicineModel::instance().purchase_medicine(medicine_name, quantity);
            }
            catch (const easymysql::except& e)
            {
                easylog::error("create purchase order failed exception: {}", e.what());
                throw model_except("create purchase order failed exception: " + std::string(e.what()));
                return false;
            }

            return true;
        }

        std::vector<PurchaseOrder> query_purchase_records(const std::string& medicine_name, const std::string& supplier, const std::string& purchase_date)
        {
            std::vector<PurchaseOrder> purchase_orders;
            try
            {
                std::ostringstream query;
                query << "SELECT medicine_name, supplier, quantity, purchase_date FROM purchase_records WHERE 1=1 ";

                if (!medicine_name.empty())
                    query << "AND medicine_name = '" << medicine_name << "' ";
                if (!supplier.empty())
                    query << "AND supplier = '" << supplier << "' ";
                if (!purchase_date.empty())
                    query << "AND purchase_date = '" << purchase_date << "' ";

                easylog::debug(query.str().c_str());

                easymysql::result res = easymysql::executer(database::instance())(query.str());

                PurchaseOrder::tuple_of_purchase_order line;
                while (res.get<PurchaseOrder::tuple_of_purchase_order>(&line))
                {
                    purchase_orders.push_back(PurchaseOrder::from_tuple_quickly(line));
                }
            }
            catch (const easymysql::except& e)
            {
                easylog::error("query purchase order failed exception: {}", e.what());
                throw model_except("query purchase order failed exception: " + std::string(e.what()));
            }

            return purchase_orders;
        }

    };
}